<script setup>
import {ref, onMounted, onUnmounted} from "vue";
import Peer from "peerjs";

const mode = ref("signal"); // "signal" 代表信令服务器模式, "manual" 代表手动模式
const channel = ref(""); // 用户输入的频道名
const message = ref("");
const messages = ref([]);
const ws = ref(null);
const peer = ref(null);
const peerId = ref("");
const remotePeerId = ref("");
const conn = ref(null);

// 1. 信令服务器模式: WebSocket 连接
const connectWebSocket = () => {
	if (!channel.value) return;
	ws.value = new WebSocket(`wss://192.168.13.90:7777/ws/${channel.value}`);

	ws.value.onmessage = (event) => {
		messages.value.push(event.data);
	};

	ws.value.onclose = () => {
		console.log("WebSocket closed");
	};
};

const sendMessage = () => {
	if (mode.value === "signal" && ws.value) {
		ws.value.send(message.value);
	} else if (mode.value === "manual" && conn.value) {
		conn.value.send(message.value);
	}
	messages.value.push(`你: ${message.value}`);
	message.value = "";
};

// 2. 手动模式: 使用 PeerJS 直接建立 P2P 连接
const setupPeer = () => {
	peer.value = new Peer();
	peer.value.on("open", (id) => {
		console.log(id)
		peerId.value = id;
	});

	peer.value.on("connection", (connection) => {
		conn.value = connection;
		conn.value.on("data", (data) => {
			messages.value.push(`对方: ${data}`);
		});
	});
};

const connectPeerManually = () => {
	if (!remotePeerId.value) return;
	conn.value = peer.value.connect(remotePeerId.value);
	conn.value.on("open", () => {
		console.log("连接成功");
	});
	conn.value.on("data", (data) => {
		messages.value.push(`对方: ${data}`);
	});
};

onMounted(() => {
	const isWebRTCSupported = () => {
		return (
			"RTCPeerConnection" in window &&
			"RTCSessionDescription" in window &&
			"RTCDataChannel" in window &&
			navigator.mediaDevices?.getUserMedia
		);
	};
	let res = isWebRTCSupported()
	console.log(res)
	setupPeer()

});

onUnmounted(() => {
	if (ws.value) ws.value.close();
	if (peer.value) peer.value.destroy();
});
const modeOptions = [
	{
		label: "信令服务器模式",
		value: "signal",
	},
	{
		label: "手动模式",
		value: "manual",
	}
]
</script>

<template>
	<n-layout class="h-full" content-class="p-2">
		<div class="w-fit flex gap-2 flex-col">
			<h2>选择模式</h2>
			<n-select v-model:value="mode" :options="modeOptions"></n-select>

			<n-flex v-if="mode === 'signal'" :wrap="false">
				<n-input v-model:value="channel" placeholder="输入频道"/>
				<n-button @click="connectWebSocket">加入频道</n-button>
			</n-flex>

			<n-flex v-if="mode === 'manual'" :wrap="false">
				<p>你的 Peer ID: {{ peerId }}</p>
				<n-input v-model:value="remotePeerId" placeholder="输入对方 Peer ID"/>
				<n-button @click="connectPeerManually">连接</n-button>
			</n-flex>
			<n-flex :wrap="false">
				<n-input v-model:value="message" placeholder="输入消息"/>
				<n-button @click="sendMessage">发送</n-button>
			</n-flex>


			<div v-for="msg in messages" :key="msg">{{ msg }}</div>
		</div>
	</n-layout>

</template>
